﻿using SFB;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.EventSystems;

namespace SceneEditor
{
    public class ScreenShotManager : MonoBehaviour
    {
        public static ScreenShotManager Instance = null;
        public MyImage MyImage;

        public MenuControl MenuControl;
        //截屏结束的位置
        private Vector3 e_pos;
        //是否绘制
        private bool isDraw;
        //绘制状态
        private bool stateDraw;
        //开始绘制
        private bool stateDrawStart;
        //截屏开始的位置
        private Vector3 s_pos;
        Rect rect;

        private void Awake()
        {
            Instance = this;
        }

        private void Update()
        {
          
            if (Input.GetKey(KeyCode.LeftControl)&& Input.GetKey(KeyCode.LeftAlt) && Input.GetKeyDown(KeyCode.A))
            {
                OnEnter();
            }
            else if (Input.GetKeyDown(KeyCode.KeypadEnter)|| Input.GetKeyDown(KeyCode.Return))
            {
                ScreenShotFuc();
            }
            else if(Input.GetKeyDown(KeyCode.Escape))
            {
                OnExit();
            }
            if (stateDraw == true)
            {
                //按下鼠标左键时，记录当前鼠标的位置为开始截屏时的位置
                if (Input.GetMouseButtonDown(0))
                {
                    stateDrawStart = true;
                    s_pos = Input.mousePosition;
                }
                //鼠标处于按下状态时
                if (Input.GetMouseButton(0)&& stateDrawStart)
                {
                    e_pos = Input.mousePosition;
                    //可以开始绘制
                    isDraw = true;
                    MyImage.UpdateData(s_pos,e_pos);
                } 
                //抬起鼠标左键时，记录当前鼠标的位置为结束截屏时的位置
                if (Input.GetMouseButtonUp(0) && stateDrawStart == true)
                {
                    //结束绘制
                    isDraw = false;
                    stateDraw = false;
                    e_pos = Input.mousePosition;
                    if (s_pos.Equals(e_pos))
                    {
                        s_pos = new Vector2(0, Screen.height);
                        e_pos = new Vector2(Screen.width, 0);
                        MyImage.UpdateData(s_pos, e_pos);
                        rect =new Rect(0,0,Screen.width,Screen.height);
                    }
                    else
                    {
                        //获取到截屏框起始点的位置，和宽高。
                        rect = new Rect(Mathf.Min(s_pos.x, e_pos.x), Mathf.Min(s_pos.y, e_pos.y), Mathf.Abs(s_pos.x - e_pos.x), Mathf.Abs(s_pos.y - e_pos.y));
                    }
                    MenuControl.OnEnter(e_pos, ScreenShotFuc);
                }
            }
        }

        void ScreenShotFuc()
        {
            //开启绘制的协程方法
            StartCoroutine(Capsture(rect));
           
            OnExit();
        }
        /// <summary>
        /// 保存截图
        /// </summary>
        /// <param name="rect"></param>
        /// <returns></returns>
        IEnumerator Capsture(Rect rect)
        {
            yield return new WaitForEndOfFrame();

            var extensions = new[] {
                new ExtensionFilter("Image Files", "png" ),
                new ExtensionFilter("Image Files",  "BMP" ),
                new ExtensionFilter("Image Files",  "jpg"),
            };

            StandaloneFileBrowser.SaveFilePanelAsync("保存截图", Application.dataPath, Tool.GetDateTime(), extensions,
                (string path) => { //文件夹（如果StreamAssets文件夹不存在，在Assets文件下创建该文件夹）

                    if (!string.IsNullOrEmpty(path))
                    {
                        //创建纹理（纹理贴图的大小和截屏的大小相同）
                        Texture2D tex = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.RGB24, false);
                        //读取像素点
                        tex.ReadPixels(rect, 0, 0);
                        //将像素点应用到纹理上，绘制图片
                        tex.Apply();
                        //将图片装换成jpg的二进制格式，保存在byte数组中（计算机是以二进制的方式存储数据）
                        byte[] result = tex.EncodeToPNG();
                        if (!Directory.Exists(Application.streamingAssetsPath))
                            Directory.CreateDirectory(Application.streamingAssetsPath);
                        File.WriteAllBytes(path, result);
                    }

                    OnExit();
                });
        }
       

        public void OnBtnClick()
        {
            OnEnter();
        }


        public void OnEnter()
        {
            if (stateDrawStart) return;
            stateDraw = true;
            s_pos = new Vector2(0, Screen.height);
            e_pos = new Vector2(Screen.width, 0);
            MyImage.OnEnter();
        }
        

        public void OnExit()
        {
            MyImage.OnExit();
            MenuControl.OnExit();
            stateDraw = false;
            stateDrawStart = false;
            isDraw = false;
        }
    }
}
